package cn.yusei.teamTribe.util;

import java.io.UnsupportedEncodingException;
import java.util.Date;
import java.util.Properties;
import java.util.regex.Pattern;

import javax.mail.MessagingException;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
import javax.mail.internet.MimeMessage.RecipientType;

import cn.yusei.teamTribe.entity.Email;
import cn.yusei.teamTribe.entity.EmailAddress;

public class EmailUtil {
	
	private static final Pattern MAIL_PATTERN = Pattern.compile("^[0-9a-zA-Z_]+@[0-9a-zA-Z]+\\.com$");

	private static final String PROTOCAL = "smtp";
	private static final String EMAIL_SMTP_HOST = "smtp.163.com";
	private static final String AUTH = "true";
	private static final String TIMEOUT = "10000";
	private static final Properties props;
	
	static
	{
		props = new Properties();
		props.setProperty("mail.transport.protocal", PROTOCAL);
		props.setProperty("mail.smtp.host", EMAIL_SMTP_HOST);
		props.setProperty("mail.smtp.auth", AUTH);
		props.setProperty("mail.smtp.timeout", TIMEOUT);
		props.setProperty("mail.smtp.connectiontimeout", TIMEOUT);
	}
	
	public static void sendEmail(String username, String password, Email email) throws UnsupportedEncodingException, MessagingException
	{
		Session session = Session.getInstance(props);
//		session.setDebug(true);		//显示发送邮件的详细信息
		MimeMessage mimeMessage = new MimeMessage(session);
		mimeMessage.setFrom(new InternetAddress(email.getFrom().getAddress(), email.getFrom().getNickName(), email.getEncoding()));
		for(EmailAddress address : email.getTo())
		{
			mimeMessage.addRecipient(RecipientType.TO, new InternetAddress(address.getAddress(), address.getNickName(), email.getEncoding()));
		}
		mimeMessage.setSubject(email.getTitle(), email.getEncoding());
		mimeMessage.setContent(email.getContent(), email.getContentType());
		mimeMessage.setSentDate(new Date());
		mimeMessage.saveChanges();
		Transport transport = session.getTransport();
		transport.connect(username, password);
		transport.sendMessage(mimeMessage, mimeMessage.getAllRecipients());
		transport.close();
	}
	
	public static boolean isMailAddress(String email)
	{
		return MAIL_PATTERN.matcher(email).matches();
	}
}
